var $table;  
var selectionIds = [];  //保存选中ids  
var sysRoleField = dataObject.sysRoleField;
$(function () {
	  var columns =[
                       {field: 'state', checkbox: true},
                       {field: 'roleName' , title: sysRoleField.roleName, sortName:'ROLE_NAME' , sortable: true,halign: 'center',align: 'center'},
                       {field: 'remark' , title: sysRoleField.remark, sortName:'REMARK' , sortable: true,halign: 'center',align: 'center'},
                       {field: 'createUserName' , title: sysRoleField.createUserName, sortName:'CREATE_BY' , sortable: true,halign: 'center',align: 'center'},
                       {field: 'createTime' , title: sysRoleField.createTime, sortName:'CREATE_TIME' , sortable: true,halign: 'center',align: 'center'},
                       {field: 'status' , title: sysRoleField.status, formatter: 'statusFormatter', sortName:'STATUS' , sortable: true,halign: 'center',align: 'center'},
                       {field: 'action', title: pageData.action, formatter: '$table.actionFormatter', events: 'actionEvents', clickToSelect: false, width: 150, halign: 'center', align: 'center'}
                   ];
    $table = new BSTable("table", 'sys/sysrole/list', columns,"toolbar",560,'roleId','ROLE_ID','sysrole');
    var queryParams = function(params) {            
         return {
         	       page: params.pageNumber,
         	       limit: params.pageSize,
         	       sidx: params.sortName,
                   order: params.sortOrder,
                   roleName:vm.search.roleName,
              //查询字段
             };
     };
	$table.setQueryParams(queryParams);
    $table.init();
});



var setting = {
		data: {
			simpleData: {
				enable: true,
				idKey: "menuId",
				pIdKey: "parentId",
				rootPId: -1
			},
			key: {
				url:"nourl",
				name : "name",
			},
            isShowDetail: false
		},
		check:{
			enable:true,
			nocheckInherit:true
		}
	};

var company_setting = {
		data: {
			simpleData: {
				enable: true,
				idKey: "companyNo",
				pIdKey: "parentId",
				rootPId: -1
			},
			key: {
				name : "companyName",
				url:"nourl"
			}
		},
		check:{
			enable:true,
			nocheckInherit:true,
			chkboxType:  { "Y": "s", "N": "s" }
		}
	};
	
var ztree;
//部门结构树
var company_ztree;



var vm = new Vue({
	el:'#app',
	data:{
		showList: true,
		title: null,
		sysRole: {			
		},
		search:{
			id:null,
			roleName:null,
			companyName:'',
			companyNo:''
		}
	},
	methods: {
		query: function () {
			defaultActions.query();
		},
		add: function(){
			vm.isShowDetail = false;
		    vm.sysRole={status:0};
			defaultActions.add(vm);
			vm.role = {};
			vm.opId = "add";
			vm.getMenuTree(null);
			vm.getCompanyTree(null);
		},
		update: function (event, id) {
            vm.isShowDetail = false;
		    defaultActions.update(id, $("#table"),$path+"/sys/sysrole/info/", vm, function(r){
		    	vm["sysRole"] = r["sysRole"];

                //处理关联详情
                var detailParam = window.location.search;
                if(detailParam != null && detailParam.indexOf("?detailId=")>=0){
                    vm.isShowDetail = true;
                }
                vm.getMenuTree(vm.sysRole.roleId);
                vm.getCompanyTree(vm.sysRole.roleId);
	        });
		},
		saveOrUpdate: function (event) {
		    $('#defaultForm').bootstrapValidator('validate');
			if($('#defaultForm').data('bootstrapValidator').isValid()){
				var nodes = ztree.getCheckedNodes(true);
				var companyNodes = company_ztree.getCheckedNodes(true);
				var menuIdList = [];
				var companyNoList = [];
				for(var i=0; i<nodes.length; i++) {
					menuIdList.push(nodes[i].menuId);
				}
				for(var i=0; i<companyNodes.length; i++){
					companyNoList.push(companyNodes[i].companyNo);
				}
				vm.sysRole.menuIdList = menuIdList;
				vm.sysRole.companyNoList = companyNoList;
				var url = vm.sysRole.roleId == null || vm.sysRole.roleId == ''? $path+"/sys/sysrole/save" : $path+"/sys/sysrole/update";
				defaultActions.saveOrUpdate(url ,vm, $("#defaultForm"),"sysRole",event);
			}
		},
		del: function (event, id) {
		    defaultActions.del(id, $path+"/sys/sysrole/delete", $("#table") ) ;
		},
		audit:function(status){
			defaultActions.audit(status , $path+"/sys/sysrole/audit?status="+status, vm);
		},
		reload: function (event) {
		    defaultActions.reload($("#table"),$("#defaultForm"),vm,"sysRole"); 
		},
		detail: function (event, id) {
			defaultActions.detail(vm, id, event);
            vm.isShowDetail = true;
		},
		getRole: function(roleId){
            var logFlag = logUrl != undefined && logUrl != "";
            if (logFlag) {
				//勾选角色所拥有的菜单
				if (ztree) {
                    var menuIds = vm.sysRole.menuIdList;
                    for(var i=0; i<menuIds.length; i++) {
                        var node = ztree.getNodeByParam("menuId", menuIds[i]);
                        ztree.checkNode(node, true, false);
                    }
				}


                //勾选角色所拥有的部门数据权限
				if (company_ztree) {
                    var companyNos = vm.sysRole.companyNoList;
                    for(var i=0; i<companyNos.length; i++) {
                        var node = company_ztree.getNodeByParam("companyNo", companyNos[i]);
                        company_ztree.checkNode(node, true, false);
                    }
				}


                if (vm.isShowDetail || logFlag) {
					if (ztree) {
                        var nodes = ztree.getNodes();
                        for(var z=0;z<nodes.length;z++){
                            changeZtreeNodeReadOnly(nodes[z]);
                        }
					}

					if (company_ztree) {
                        var companyNodes = company_ztree.getNodes();
                        for(var c=0;c<companyNodes.length;c++){
                            changeCompanyZtreeNodeReadOnly(companyNodes[c]);
                        }
					}

                }
			} else {
                $.get($path+"/sys/sysrole/info/"+roleId, function(r){
                    vm.sysRole = r["sysRole"];
                    //勾选角色所拥有的菜单
                    var menuIds = vm.sysRole.menuIdList;
                    for(var i=0; i<menuIds.length; i++) {
                        var node = ztree.getNodeByParam("menuId", menuIds[i]);
                        if (node) {
                            ztree.checkNode(node, true, false);
						}
                    }

                    //勾选角色所拥有的部门数据权限
                    var companyNos = vm.sysRole.companyNoList;
                    for(var i=0; i<companyNos.length; i++) {
                        var node = company_ztree.getNodeByParam("companyNo", companyNos[i]);
                        if (node) {
                            company_ztree.checkNode(node, true, false);
						}
                    }

                    if (vm.isShowDetail || logFlag) {
                        var nodes = ztree.getNodes();
                        for(var z=0;z<nodes.length;z++){
                            changeZtreeNodeReadOnly(nodes[z]);
                        }

                        var companyNodes = company_ztree.getNodes();
                        for(var c=0;c<companyNodes.length;c++){
                            changeCompanyZtreeNodeReadOnly(companyNodes[c]);
                        }
                    }
                });
			}
		},
		getMenuTree: function(roleId) {
			//加载菜单树
			$.get($path+"/sys/menu/perms", function(r){
                ztree = $.fn.zTree.init($("#menuTree"), setting, r.menuList);
                //展开所有节点
                //ztree.expandAll(true);

                var nodes = ztree.getNodes();
                for(var i=0;i<nodes.length;i++){
                    changeNodeName(nodes[i]);
                }

                if(roleId != null){
                    vm.getRole(roleId);
                }
			});
	    },
	    getCompanyTree: function(roleId){
            //加载部门树
            $.get($path+"/bus/buscompany/treelist?status=2", function(r){
            	if (r.code == 0) {
                    company_ztree = $.fn.zTree.init($("#companyTree"), company_setting, r.companyList);
                    //展开所有节点
                    company_ztree.expandAll(true);
                    var nodes = company_ztree.getNodes();
                    for(var i=0;i<nodes.length;i++){
                        if(nodes[i].companyId == 'operationCenter'){
                            nodes[i].companyName = pageData.operationCenter;
                            company_ztree.updateNode(nodes[i]);
                        }
                    }
                    if(roleId != null){
                        vm.getRole(roleId);
                    }
				} else {
                    company_ztree = $.fn.zTree.init($("#companyTree"), company_setting, []);
				}
            })
        },
		showCompany:function(){
			defaultActions.assiot(pageData.compList , "../dialog/company_dialog.html",function(dialog){
				var rows =$("#table_dialog").bootstrapTable('getSelections');
				if (rows.length > 0) {
			  		
					//	vm.search.materialLibNo = rows[0].id;
						vm.search.companyName = rows[0].companyName;
						vm.search.companyNo = rows[0].companyNo;
				}else {
				//	vm.search.materialLibNo  = '';
					vm.search.companyName = '';
					vm.search.companyNo = '';
				}
				dialog.close();
			});
		}
	}
});

function changeNodeName(node){
	if (node.isParent) {
		var childrenNodes = node.children;
		if (childrenNodes) {
			for (var i = 0; i < childrenNodes.length; i++) {
				 changeNodeName(childrenNodes[i]);
			}
		}
	}
	node.name = menuData[node.name];
	ztree.updateNode(node);
}

function changeZtreeNodeReadOnly(node) {
    if (node.isParent) {
        var childrenNodes = node.children;
        if (childrenNodes) {
            for (var i = 0; i < childrenNodes.length; i++) {
                changeZtreeNodeReadOnly(childrenNodes[i]);
            }
        }
    }
    ztree.setChkDisabled(node, true);
}
function changeCompanyZtreeNodeReadOnly(node) {
    if (node.isParent) {
        var childrenNodes = node.children;
        if (childrenNodes) {
            for (var i = 0; i < childrenNodes.length; i++) {
                changeCompanyZtreeNodeReadOnly(childrenNodes[i]);
            }
        }
    }
    company_ztree.setChkDisabled(node, true);
}

/*表单校验 start*/
$('#defaultForm').bootstrapValidator({
    feedbackIcons: vail.feedbackIcons(),
    fields: {
               roleName: vail.REPEATREGEX("角色名称",sysRoleField.roleName,"20",$path+"/sys/sysrole/checkExist","sysRole","roleId","roleName","ROLE_NAME",/^[\S]*$/,"不能有空格"),
               remark: vail.NOTNULLLIMIT("角色描述",sysRoleField.remark,1,150),
		    
    }
});
/*表单校验 end*/
